package main

import (
	"fmt"
	"io"
	"net"
	"sync"
)

type Server struct {
	Ip   string
	Port int

	//在綫用戶列表
	OnlineMap map[string]*User
	maplock   sync.RWMutex //用戶列表讀寫鎖

	//消息廣播的channel
	Message chan string
}

//创建一个server的接口
func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
	return server
}

//監聽Message channel的goroutine,一旦有消息就發送給全部的在綫user
func (T *Server) ListenMessagrer() {
	for {
		msg := <-T.Message
		//將msg發送給全部的在綫user
		T.maplock.Lock()
		for _, cli := range T.OnlineMap {
			cli.C <- msg

		}
		T.maplock.Unlock()
	}
}

func (T *Server) Handler(conn net.Conn) {
	//通過conn創建一個User
	user := NewUser(conn)
	//將用戶加入在綫列表
	T.maplock.Lock()
	T.OnlineMap[user.Name] = user
	T.maplock.Unlock()
	//廣播用戶上綫消息
	T.BroadCast(user, "已上綫")

	//接受客戶端發送的消息
	go func() {
		buf := make([]byte, 4096)
		for {
			n, err := conn.Read(buf)
			if n == 0 {
				T.BroadCast(user, "已下綫")
				return
			}
			if err != nil && err != io.EOF {
				fmt.Println("Conn Read err:", err)
				return
			}
			//提取用戶的消息(去除"\n")
			msg := string(buf[:n-1])
			T.BroadCast(user, msg)
		}
	}()
	select {}
}

func (T *Server) BroadCast(user *User, msg string) {
	sendMsg := "[" + user.Addr + "]" + user.Name + ":" + msg
	T.Message <- sendMsg
}

//启动服务器的接口
func (T *Server) Start() {
	//socket listen
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", T.Ip, T.Port))
	if err != nil {
		fmt.Println("net.Listen err:", err)
		return
	}
	//close listen socket
	defer listener.Close()
	//啓動監聽Message channel中是否有數據的goroutine
	go T.ListenMessagrer()

	for {
		//accept
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("listener accept err:", err)
			continue
		}
		//do handler
		go T.Handler(conn)
	}

	//close listen socket
}
